package com.allwees.bs.c.module.order.context.compute.strategy.coupon;

import com.allwees.bs.c.module.order.context.bo.CouponComputeBo;
import com.allwees.bs.c.module.order.context.bo.CouponComputeItemBo;
import com.allwees.bs.c.module.order.context.bo.UserCouponBo;
import com.allwees.bs.core.model.user.constant.ECouponDefType;
import com.allwees.core.common.util.MoneyUtil;

import java.math.BigDecimal;
import java.util.List;

/**
 * 满减券
 */
public class CouponDeductStrategy extends CouponStrategy {

    @Override
    public boolean isSupport(UserCouponBo coupon) {
        if (coupon == null) {
            return false;
        }
        return ECouponDefType.DEDUCT.equals(coupon.getCouponType()) && coupon.getFaceValue() != null;
    }

    @Override
    public CouponComputeBo use(UserCouponBo coupon, CouponComputeBo computeBo) {
        return useDeductAmt(coupon.getFaceValue(), computeBo);
    }

    public static CouponComputeBo useDeductAmt(BigDecimal maxDeductAmt, CouponComputeBo computeBo) {
        List<CouponComputeItemBo> items = computeBo.getItems();

        BigDecimal ratio = ratio(maxDeductAmt, computeBo.getAmtProduct());

        BigDecimal amtProduct = BigDecimal.ZERO;

        BigDecimal amtProductDiscount = BigDecimal.ZERO;
        int length = items.size();
        for (int i = 0; i < length; i++) {
            CouponComputeItemBo item = items.get(i);
            BigDecimal temp = item.getAmtSku();
            //sub(computeBo.getAmtProduct(), maxDeductAmt) 是  商品实付总金额减去最大优惠金额之后剩下的需要付的总金额, sub(sub(computeBo.getAmtProduct(), maxDeductAmt), amtProduct) 是最后一个商品需要付的钱
            item.setAmtSku(last(length, i) ? sub(sub(computeBo.getAmtProduct(), maxDeductAmt), amtProduct) : realAmtProduct(item.getAmtSku(), ratio));

            //item.setAmtProductCoupon(MoneyUtil.sub(temp, item.getAmtSku()));//sku商品优惠金额
            item.setAmtProductDiscountSku(MoneyUtil.sub(temp, item.getAmtSku()));//sku商品优惠金额
            item.computeAmt();
            amtProductDiscount= MoneyUtil.add(amtProductDiscount,item.getAmtProductDiscountSku());
            amtProduct = MoneyUtil.add(amtProduct, item.getAmtSku());


        }
        //商品优惠
        computeBo.setAmtProductCoupon(amtProductDiscount);
        computeBo.setAmtProduct(amtProduct);
        return computeBo.computeAmt();
    }

    protected static BigDecimal realAmtProduct(BigDecimal amtProduct, BigDecimal ratio) {
        return MoneyUtil.sub(amtProduct, mul(amtProduct, ratio));
    }

    private static BigDecimal ratio(BigDecimal maxDeductAmt, BigDecimal amtProduct) {
        return MoneyUtil.div(maxDeductAmt, amtProduct, 10);
    }
}
